export default {
	// 为当前模块开启命名空间
	namespaced:true,
	
	// 模块的state数据
	state:()=>({
		// 购物车的数组，用来存储购物车中每个商品的信息对象
		// 每个商品的信息对象，都包含如下6给属性
		//goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state
		cart:JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	// 模块的mutations方法
	mutations:{
		addToCart(state,goods){
			const result = state.cart.find(item=>{
				return item.goods_id === goods.goods_id
			})
			// console.log(result)
			if(!result){
				// 表示购物车里没有这件商品
				state.cart.push(goods)
			}
			else{
				// 表示购物车里有这件商品那么就让count+1
				result.goods_count++
			}
			this.commit('m_cart/saveToStorage')
			// console.log(state.cart)
		},
		saveToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		updateState(state,goods){
			const result = state.cart.find(item=>item.goods_id === goods.goods_id);
			if(result){
				result.goods_state = goods.goods_state;
				this.commit('m_cart/saveToStorage')
			}
		},
		updateCount(state,goods){
			const result = state.cart.find(item=>item.goods_id === goods.goods_id);
			if(result){
				result.goods_count = goods.goods_count;
				// console.log(result)
				this.commit('m_cart/saveToStorage')
			}
		},
		removeGoodsById(state,goods_id){
			state.cart = state.cart.filter(item=> item.goods_id != goods_id);
			this.commit('m_cart/saveToStorage')
		},
		updateAllGoods(state,newState){
			state.cart.forEach(x=>x.goods_state = newState);
			this.commit('m_cart/saveToStorage')
		}
		
	},
	
	// 模块的getters属性
	getters:{
		// 购物车中所有商品的数量
		total(state){
			let c = 0;
			state.cart.forEach(item=> c += item.goods_count)
			return c;
		},
		// 勾选商品的总数量
		checkedCount(state){
		return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count,0)
		},
		// 显示总价格
		showPrice(state){
			return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_price*item.goods_count,0)
		}
	}
}
